﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using libStorage;

namespace libCouchStorage.JSON
{
    class JSONWriter
    {
         public static string ToJavaScriptObjectNotation(object obj)
            {
                var strBld = new StringBuilder("{"); 
             Type objType = obj.GetType();
                bool firstIter = true;
                foreach (FieldInfo fieldInfo in objType.GetFields(BindingFlags.Public | BindingFlags.Instance))
                {
                    foreach (StorableField atrb in fieldInfo.GetCustomAttributes(typeof(StorableField), false))
                    {
                        if (!firstIter) strBld.Append(", ");
                        strBld.AppendFormat("\"{0}\":{1}", atrb.Name, GetJsonStringForFieldValue(fieldInfo, obj));
                        firstIter = false;
                    }

                   
                } 
                strBld.Append("}");
                return strBld.ToString();
            }
            private static string GetJsonStringForFieldValue(FieldInfo field, object obj)
            {
                string val = "";
                string typeName = field.FieldType.FullName;
                switch (typeName)
                { 
                    case "System.DateTime":   
                        TimeSpan ts = (DateTime)field.GetValue(obj) - DateTime.Parse("1/1/1970");
                        val = " new Date(" + ts.TotalMilliseconds.ToString() + ")";
                        break;
                    case "System.String":
                        val = "\"" + (string)field.GetValue(obj) + "\"";
                        break;
                    default:  
                        val = field.GetValue(obj).ToString();
                        break;
                } 
                return val;
            }
        }
    }

